import React, { Component } from "react";
import { Button, Table, Divider, message, Popconfirm } from "antd";
import { connect } from "dva";
import { Link } from "dva/router";
import moment from "moment";
import tableFilter from "../../../../components/tableFilter";
import styles from "./CustomMade.less";

@connect(stores => ({
  stData: stores.situationList,
  orgData: stores.adddataSource
}))
@tableFilter
class CustomMade extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ownerDept: [],
      rank: "desc",
      pageNum: 1,
      pageSize: 10,
      selectData: []
    };
  }

  componentDidMount() {
    this.filterFun();
    this.setDepart();
  }

  setDepart = () => {
    const { dispatch } = this.props;
    dispatch({
      type: "situationList/departData",
      payload: {}
    }).then(() => {
      const { stData } = this.props;
      const { departList = [] } = stData;
      const dep = [];
      departList.forEach(item => {
        dep.push({ text: item.ownerDeptName, value: item.ownerDept });
      });
      this.setState({
        selectData: dep
      });
    });
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { ownerDept } = this.state;
    // const { dispatch, search } = this.props;
    // if (filters.ownerDeptName && filters.ownerDeptName.length === 1) {
    this.setState(
      {
        pageNum:
          filters.ownerDeptName && filters.ownerDeptName !== ownerDept
            ? "1"
            : String(current),
        pageSize: String(pageSize),
        rank: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        ownerDept: filters.ownerDeptName ? filters.ownerDeptName : []
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const { ownerDept, pageSize, rank, pageNum } = this.state;
    const { search } = this.props;
    const { dispatch } = this.props;
    dispatch({
      type: "situationList/getSituationList",
      payload: {
        pageNum,
        pageSize,
        rank,
        ownerDept: ownerDept[0],
        content: search === "" ? undefined : search
      }
    });
    dispatch({
      type: "situationList/departData",
      payload: {
        rank,
        ownerDept: ownerDept[0],
        content: search === "" ? undefined : search
      }
    }).then(() => {
      const { stData } = this.props;
      const { departList = [] } = stData;
      const dep = [];
      departList.forEach(item => {
        dep.push({ text: item.ownerDeptName, value: item.ownerDept });
      });
      this.setState({
        selectData: dep
      });
    });
  };

  delScene = id => {
    const { dispatch } = this.props;
    dispatch({
      type: "situationList/delSecen",
      payload: { sceneTemplateId: id }
    }).then(() => {
      const { stData } = this.props;
      const { delErrCode, delErrMsg } = stData;
      if (delErrCode === 0) {
        message.success("删除成功");
        const { pageSize, ownerDept } = this.state;
        this.setState({
          pageNum: 1,
          rank: "desc"
        });
        dispatch({
          type: "situationList/getSituationList",
          payload: {
            pageNum: 1,
            pageSize,
            rank: "desc",
            ownerDept: ownerDept[0]
          }
        });
        this.setDepart();
      } else {
        message.error(delErrMsg);
      }
    });
  };

  render() {
    const { stData, getColumnSearchProps = () => {} } = this.props;
    const { pageNum } = this.state;
    const newSel = [];
    const delDuplicate = [];
    this.state.selectData.forEach(item => {
      newSel.push(item.value);
    });
    const temp = [];
    newSel.forEach((item, index) => {
      if (temp.indexOf(item) === -1) {
        temp.push(item);
        delDuplicate.push(this.state.selectData[index]);
      }
    });
    const columns = [
      {
        title: "场景名称",
        dataIndex: "templateName",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "场景描述",
        dataIndex: "templateDescription",
        render: text => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden"
            }}
          >
            {text}
          </span>
        )
      },
      {
        title: "归属部门",
        dataIndex: "ownerDeptName",
        ...getColumnSearchProps(delDuplicate)
      },
      {
        title: "数据源名称",
        dataIndex: "dsName"
      },
      {
        title: "管理员",
        dataIndex: "owner",
        render: text =>
          JSON.parse(text) && JSON.parse(text).length > 0
            ? JSON.parse(text)[0].name
            : "-"
      },
      {
        title: "创建时间",
        dataIndex: "timeCreate",
        sorter: true,
        defaultSortOrder: "descend",
        render: (text, record) =>
          moment(record.timeCreate).format("YYYY-MM-DD HH:mm:ss")
      },
      {
        title: "操作",
        dataIndex: "operate",
        width: 120,
        render: (text, record) => {
          const states = {
            operate: "mod",
            sceneTemplateId: record.sceneTemplateId
          };
          const keys = {
            sceneTemplateId: record.sceneTemplateId
          };
          return (
            <span>
              <Link
                to={`/intellPush/recommendCenter/situation/sceneDetail?key=${JSON.stringify(
                  keys
                )}`}
              >
                详情
              </Link>
              <Divider type="vertical" />
              <Link
                to={`/intellPush/recommendCenter/situation/editScene?key=${JSON.stringify(
                  states
                )}`}
                disabled={!record.dataPrivilege}
              >
                编辑
              </Link>
              <Divider type="vertical" />
              <Popconfirm
                title={`你是否要删除${record.templateName}?`}
                onConfirm={() => this.delScene(record.sceneTemplateId)}
                // onCancel={}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <a disabled={record.inService || !record.dataPrivilege}>删除</a>
              </Popconfirm>
            </span>
          );
        }
      }
    ];
    const { STList = [], loading, totalCount } = stData;
    const states = { operate: "add" };
    return (
      <div className={styles.root}>
        <Link
          to={`/intellPush/recommendCenter/situation/addScene?key=${JSON.stringify(
            states
          )}`}
        >
          <Button type="primary" style={{ marginBottom: 16 }}>
            新增
          </Button>
        </Link>
        <Table
          rowKey={record => record.sceneTemplateId}
          columns={columns}
          size="middle"
          locale={{ emptyText: "暂无数据！" }}
          dataSource={STList}
          loading={loading}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum * 1,
            total: totalCount,
            showTotal: total => `共有 ${total} 条`
          }}
        />
      </div>
    );
  }
}

export default CustomMade;
